package com.ytktt.study.week12.task4.task;

import com.ytktt.study.week12.task4.redis.constant.RedisConstant;
import com.ytktt.study.week12.task4.util.CurDateStringUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Set;

/**
 * 处理 RedisKey 的任务
 *
 * @author ytk
 */
@Configuration
@EnableScheduling
@RequiredArgsConstructor
public class HandleRedisKeyTask {

    private final CurDateStringUtil curDateStringUtil;
    private final RedisTemplate<String, Object> redisTemplate;

    @Scheduled(cron = "0 0 0 * * ?")
    public void configureTasks() {
        this.curDateStringUtil.genCurDateString();
        LocalDate beforeThreeDay = LocalDate.now().minusDays(3L);
        DateTimeFormatter dtf = this.curDateStringUtil.getDateTimeFormatter();
        String seqKey = String.format(RedisConstant.ORDER_PRODUCER_MESSAGE_SEQ + ":*", dtf.format(beforeThreeDay));
        Set<String> keys = this.redisTemplate.keys(seqKey);
        if (CollectionUtils.isNotEmpty(keys)) {
            this.redisTemplate.delete(keys);
        }
    }
}
